using System.Collections.Generic;
using UnityEngine;

namespace NodeCanvas.BehaviourTrees
{
	[AddComponentMenu("")]
	[Name("Sequencer")]
	[Category("Composites")]
	[Description("Execute the child nodes in order or randonly and return Success if all children return Success, else return Failure\nIf is Dynamic, higher priority child status is revaluated. If a child returns Failure the Sequencer will bail out immediately in Failure too.")]
	[Icon("Sequencer")]
	public class BTSequencer : BTComposite
	{
		public bool isDynamic;

		public bool isRandom;

		private int lastRunningNodeIndex;

		public override string nodeName
		{
			get
			{
				return string.Format("<color=#bf7fff>{0}</color>", base.nodeName.ToUpper());
			}
		}

		protected override Status OnExecute(Component agent, Blackboard blackboard)
		{
			for (int i = ((!isDynamic) ? lastRunningNodeIndex : 0); i < base.outConnections.Count; i++)
			{
				base.status = base.outConnections[i].Execute(agent, blackboard);
				if (base.status == Status.Running)
				{
					if (isDynamic && i < lastRunningNodeIndex)
					{
						base.outConnections[lastRunningNodeIndex].ResetConnection();
					}
					lastRunningNodeIndex = i;
					return base.status;
				}
				if (base.status == Status.Failure)
				{
					if (isDynamic && i < lastRunningNodeIndex)
					{
						base.outConnections[lastRunningNodeIndex].ResetConnection();
					}
					return base.status;
				}
			}
			return Status.Success;
		}

		protected override void OnReset()
		{
			lastRunningNodeIndex = 0;
			if (isRandom)
			{
				base.outConnections = Shuffle(base.outConnections);
			}
		}

		public override void OnPortDisconnected(int index)
		{
			if (index != 0 && index == lastRunningNodeIndex)
			{
				lastRunningNodeIndex--;
			}
		}

		public override void OnGraphStarted()
		{
			OnReset();
		}

		private List<Connection> Shuffle(List<Connection> list)
		{
			for (int num = list.Count - 1; num > 0; num--)
			{
				int index = (int)Mathf.Floor(Random.value * (float)(num + 1));
				Connection value = list[num];
				list[num] = list[index];
				list[index] = value;
			}
			return list;
		}
	}
}
